
package com.putao.album.util;

import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface.OnClickListener;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.Matrix;
import android.media.ExifInterface;
import android.os.Environment;

import com.putao.album.application.GlobalApplication;
import com.putao.album.fileupload.FileUploadManager;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigInteger;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
import java.security.MessageDigest;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

public class CommonUtils {
    /**
     * 获取应用的数据存储目录
     *
     * @return
     */
    public static String getExternalFilePath() {
        String path = GlobalApplication.getInstance().getExternalFilesDir(null).getPath();
        File noMedia = new File(path, ".nomedia");
        if (!noMedia.exists()) {
            try {
                noMedia.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return path;
    }

    /**
     *
     * @return
     */
    public static File getOutputMediaDir() {
        File mediaStorageDir = new File(Environment.getExternalStorageDirectory(),
                PuTaoConstants.SYSTEM_CAMERA_FOLDER);
        if (!mediaStorageDir.exists()) {
            if (!mediaStorageDir.mkdirs()) {
                return null;
            }
        }
        return mediaStorageDir;
    }

    /**
     * 生成一个当前时间的jpg图片名字
     *
     * @return
     */
    public static File getOutputMediaFile() {
        // Create a media file name
        String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss_SS").format(new Date());
        File mediaFile;
        mediaFile = new File(getOutputMediaDir() + File.separator + "IMG_" + timeStamp + ".jpg");
        return mediaFile;
    }

    public static Dialog dialog(Context context, String message, String b1text, String b2text, OnClickListener... listeners) {
        AlertDialog.Builder builder = new AlertDialog.Builder(context);
        builder.setMessage(message);
        return builder.show();
    }


    public static String parseTime(Object time, String type) {
        DateFormat fmt = new SimpleDateFormat(type);
        Date date = null;
        if (time instanceof Long) {
            date = new Date((Long) time);
        } else if (time instanceof String) {
            try {
                date = fmt.parse(String.valueOf(time));
            } catch (ParseException e) {
                e.printStackTrace();
            }
        }
        return fmt.format(date);
    }


    public static void saveBabyId(String babyId) {
        SharedPreferencesHelper.saveStringValue(GlobalApplication.getInstance(), PuTaoConstants.PREFERENCE_KEY_BABY_ID, babyId);

        FileUploadManager.getIntance().startUploadCurrentChildUnfinished(babyId);
    }

    public static String getBabyId() {
        return SharedPreferencesHelper.readStringValue(GlobalApplication.getInstance(), PuTaoConstants.PREFERENCE_KEY_BABY_ID,PuTaoConstants.DEVAULT_BABY_ID);
    }

    /**
     * 获取用户登录成功的ID
     *
     * @return String
     */
    public static String getUsrId() {
        return SharedPreferencesHelper.readStringValue(GlobalApplication.getInstance(), PuTaoConstants.PREFERENCE_KEY_UID, null);
    }

    /**
     * 获取用户登录成功后的Token
     *
     * @return
     */
    public static String getTokenId() {
        return SharedPreferencesHelper.readStringValue(GlobalApplication.getInstance(), PuTaoConstants.PREFERENCE_KEY_TOKEN, null);
    }

    public static void saveBabyName(String babyName) {
        SharedPreferencesHelper.saveStringValue(GlobalApplication.getInstance(), PuTaoConstants.PREFERENCE_KEY_BABY_NAME, babyName);
    }

    public static void saveBabyAge(String babyAge) {
        SharedPreferencesHelper.saveStringValue(GlobalApplication.getInstance(), PuTaoConstants.PREFERENCE_KEY_BABY_AGE, babyAge);
    }

    public static void saveCurBabyIconUrl(String babyAge) {
        SharedPreferencesHelper.saveStringValue(GlobalApplication.getInstance(), PuTaoConstants.PREFERENCE_KEY_BABY_ICON_URL, babyAge);
    }
    public static String getCurBabyIconUrl() {
        return SharedPreferencesHelper.readStringValue(GlobalApplication.getInstance(), PuTaoConstants.PREFERENCE_KEY_BABY_ICON_URL, "");
    }
    public static String getBabyName() {
        return SharedPreferencesHelper.readStringValue(GlobalApplication.getInstance(), PuTaoConstants.PREFERENCE_KEY_BABY_NAME, "-1");
    }

    public static String getBabyAge() {
        return SharedPreferencesHelper.readStringValue(GlobalApplication.getInstance(), PuTaoConstants.PREFERENCE_KEY_BABY_AGE, "-1");

    }

    public static void saveRelationShip(String relationship) {
        SharedPreferencesHelper.saveStringValue(GlobalApplication.getInstance(), PuTaoConstants.PREFERENCE_KEY_RELATIONSHIP, relationship);
    }

    public static String getRelationShip() {
        return SharedPreferencesHelper.readStringValue(GlobalApplication.getInstance(), PuTaoConstants.PREFERENCE_KEY_RELATIONSHIP, "-1");
    }

    public static String getUmengDeviceToken() {
        return SharedPreferencesHelper.readStringValue(GlobalApplication.getInstance(), PuTaoConstants.PREFERENCE_KEY_UMENG_DEVICE_TOKEN, "");
    }

    public static boolean isOnlyWifiUploadOpen() {
        return SharedPreferencesHelper.readBooleanValue(GlobalApplication.getInstance(), PuTaoConstants.PREFERENCE_KEY_UP_DOWN_ONLY_WIFI, true);
    }

    public static boolean isBackgroundUploadOpen() {
        return SharedPreferencesHelper.readBooleanValue(GlobalApplication.getInstance(), PuTaoConstants.PREFERENCE_KEY_COUNTINUTE_UPLOAD_BACKGROUND, true);
    }
    /**
     * 标识是否有新消息
     *
     * @param flag
     */
    public static void setNewMessageFlag(boolean flag) {
        SharedPreferencesHelper.saveBooleanValue(GlobalApplication.getInstance(), PuTaoConstants.PREFERENCE_KEY_FLAG_NEW_MESSAGE, flag);
    }

    /**
     * 获取是否有新消息
     *
     * @return
     */
    public static boolean getNewMessageFlag() {
        return SharedPreferencesHelper.readBooleanValue(GlobalApplication.getInstance(), PuTaoConstants.PREFERENCE_KEY_FLAG_NEW_MESSAGE, false);
    }


    /**
     * 获取文件的MD5值
     *
     * @param file
     * @return
     * @throws FileNotFoundException
     */
    public static String getMd5ByFile(File file) {
        long time = System.currentTimeMillis();
        String value = null;
        FileInputStream in = null;
        try {
            in = new FileInputStream(file);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        try {
            MappedByteBuffer byteBuffer = in.getChannel().map(FileChannel.MapMode.READ_ONLY, 0, file.length());
            MessageDigest md5 = MessageDigest.getInstance("MD5");
            md5.update(byteBuffer);
            BigInteger bi = new BigInteger(1, md5.digest());
            value = bi.toString(16);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (null != in) {
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
//        Loger.d("chen+++++getMd5ByFile(),time=" + (System.currentTimeMillis() - time) + ",md5:" + value + ",fileSize:" + file.length() / 1024 + "KB");
        return value;
    }

    /**
     * 获取文件头3000byte的SHA1值
     *
     * @param file
     * @return
     */
    public static String getFileHeadHash(File file) {
        long time = System.currentTimeMillis();
        InputStream inputStream = null;
        String value = null;
        try {
            inputStream = new FileInputStream(file); // Create an FileInputStream instance according to the filepath
            byte[] buffer = new byte[3000]; // The buffer to read the file
            MessageDigest digest = MessageDigest.getInstance("SHA-1"); // Get a SHA-1 instance
            int numRead = 0; // Record how many bytes have been read

            numRead = inputStream.read(buffer);
            if (numRead > 0)
                digest.update(buffer, 0, numRead); // Update the digest

            byte[] sha1Bytes = digest.digest(); // Complete the hash computing
            String t = new String(buffer);
            value = convertHashToString(sha1Bytes); // Call the function to convert to hex digits
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (inputStream != null) {
                try {
                    inputStream.close(); // Close the InputStream
                } catch (Exception e) {
                }
            }
           // Loger.d("chen+++++getFileHeadHash(),time=" + (System.currentTimeMillis() - time)+",value:"+value);
        }
        return value;
    }

    /**
     * 获取文件的SHA-1值,速度比get SHA1 By File()快
     * @param file
     * @return
     */
    public static String getHashByFile(File file) {
        long time = System.currentTimeMillis();
        String value = null;
        FileInputStream in = null;
        try {
            in = new FileInputStream(file);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        try {
            MappedByteBuffer byteBuffer = in.getChannel().map(FileChannel.MapMode.READ_ONLY, 0, file.length());
            MessageDigest md5 = MessageDigest.getInstance("SHA-1");
            md5.update(byteBuffer);
            BigInteger bi = new BigInteger(1, md5.digest());
            value = bi.toString(16);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (null != in) {
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        //Loger.d("chen+++++getHashByFile(),time=" + (System.currentTimeMillis() - time) + ",md5:" + value + ",fileSize:" + file.length() / 1024 + "KB");
        return value;
    }
    /**
     * 获取文件的SHA1值
     *
     * @param file
     * @return
     */
    public static String getSHA1ByFile(File file) {
        long time = System.currentTimeMillis();
        InputStream inputStream = null;
        String value = null;
        try {
            inputStream = new FileInputStream(file); // Create an FileInputStream instance according to the filepath
            byte[] buffer = new byte[1024]; // The buffer to read the file
            MessageDigest digest = MessageDigest.getInstance("SHA-1"); // Get a SHA-1 instance
            int numRead = 0; // Record how many bytes have been read
            while (numRead != -1) {
                numRead = inputStream.read(buffer);
                if (numRead > 0)
                    digest.update(buffer, 0, numRead); // Update the digest
            }
            byte[] sha1Bytes = digest.digest(); // Complete the hash computing
            String t = new String(buffer);
            value = convertHashToString(sha1Bytes); // Call the function to convert to hex digits
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (inputStream != null) {
                try {
                    inputStream.close(); // Close the InputStream
                } catch (Exception e) {
                }
            }
//            Loger.d("chen+++++fileToSHA1(),time=" + (System.currentTimeMillis() - time));
        }
        return value;
    }

    private static String convertHashToString(byte[] hashBytes) {
        String returnVal = "";
        for (int i = 0; i < hashBytes.length; i++) {
            returnVal += Integer.toString((hashBytes[i] & 0xff) + 0x100, 16).substring(1);
        }
        return returnVal.toLowerCase();
    }


    public static void fileChannelCopy(File s, File t) {

        FileInputStream fi = null;
        FileOutputStream fo = null;
        FileChannel in = null;
        FileChannel out = null;
        try {
            fi = new FileInputStream(s);
            fo = new FileOutputStream(t);
            in = fi.getChannel();//得到对应的文件通道
            out = fo.getChannel();//得到对应的文件通道
            in.transferTo(0, in.size(), out);//连接两个通道，并且从in通道读取，然后写入out通道

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                fi.close();
                in.close();
                fo.close();
                out.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 获取图片的旋转角度
     *
     * @param filePath
     * @return
     */
    public static int getImageFileDegree(String filePath) {
        int degree = 0;
        try {
            // 从指定路径下读取图片，并获取其EXIF信息
            ExifInterface exifInterface = new ExifInterface(filePath);
            // 获取图片的旋转信息
            int orientation = exifInterface.getAttributeInt(ExifInterface.TAG_ORIENTATION,
                    ExifInterface.ORIENTATION_NORMAL);
            switch (orientation) {
                case ExifInterface.ORIENTATION_ROTATE_90:
                    degree = 90;
                    break;
                case ExifInterface.ORIENTATION_ROTATE_180:
                    degree = 180;
                    break;
                case ExifInterface.ORIENTATION_ROTATE_270:
                    degree = 270;
                    break;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return degree;
    }

    /**
     * 获取图片的旋转角度
     *
     * @param filePath
     * @return
     */
    public static int getImageFileOrientation(String filePath) {
        try {
            // 从指定路径下读取图片，并获取其EXIF信息
            ExifInterface exifInterface = new ExifInterface(filePath);
            // 获取图片的旋转信息
            int orientation = exifInterface.getAttributeInt(ExifInterface.TAG_ORIENTATION,
                    ExifInterface.ORIENTATION_NORMAL);
            return orientation;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return ExifInterface.ORIENTATION_NORMAL;
    }


    /**
     * Takes an orientation and a bitmap, and returns the bitmap transformed
     * to that orientation.
     */
    public static Bitmap orientBitmap(Bitmap bitmap, int ori) {
        Matrix matrix = new Matrix();
        int w = bitmap.getWidth();
        int h = bitmap.getHeight();
        if (ori == ExifInterface.ORIENTATION_ROTATE_90 ||
                ori == ExifInterface.ORIENTATION_ROTATE_270 ||
                ori == ExifInterface.ORIENTATION_TRANSPOSE ||
                ori == ExifInterface.ORIENTATION_TRANSVERSE) {
            int tmp = w;
            w = h;
            h = tmp;
        }
        switch (ori) {
            case ExifInterface.ORIENTATION_ROTATE_90:
                matrix.setRotate(90, w / 2f, h / 2f);
                break;
            case ExifInterface.ORIENTATION_ROTATE_180:
                matrix.setRotate(180, w / 2f, h / 2f);
                break;
            case ExifInterface.ORIENTATION_ROTATE_270:
                matrix.setRotate(270, w / 2f, h / 2f);
                break;
            case ExifInterface.ORIENTATION_FLIP_HORIZONTAL:
                matrix.preScale(-1, 1);
                break;
            case ExifInterface.ORIENTATION_FLIP_VERTICAL:
                matrix.preScale(1, -1);
                break;
            case ExifInterface.ORIENTATION_TRANSPOSE:
                matrix.setRotate(90, w / 2f, h / 2f);
                matrix.preScale(1, -1);
                break;
            case ExifInterface.ORIENTATION_TRANSVERSE:
                matrix.setRotate(270, w / 2f, h / 2f);
                matrix.preScale(1, -1);
                break;
            case ExifInterface.ORIENTATION_NORMAL:
            default:
                return bitmap;
        }
        return Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(),
                bitmap.getHeight(), matrix, true);
    }


    /**
     *判断应用是否安装
     * @param context
     * @param packageName
     * @return
     */
    public static boolean isAppInstalled(Context context, String packageName) {
        final PackageManager packageManager = context.getPackageManager();
        List<PackageInfo> pinfo = packageManager.getInstalledPackages(0);
        List<String> pName = new ArrayList<String>();
        if (pinfo != null) {
            for (int i = 0; i < pinfo.size(); i++) {
                String pn = pinfo.get(i).packageName;
                pName.add(pn);
            }
        }
        return pName.contains(packageName);
    }
}
